class Solution {
    public int[] intersect(int[] nums1, int[] nums2) {
                HashMap<Integer, Integer> map = new HashMap();
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < nums1.length; i++) {
            Integer cnt = map.get(nums1[i]);
            cnt = cnt == null ? 0 : cnt;
            map.put(nums1[i], cnt + 1);
        }
        for (int i = 0; i < nums2.length; i++) {
            if (map.containsKey(nums2[i])) {
                int cnt = map.get(nums2[i]);
                if (cnt > 1) {
                    map.put(nums2[i], cnt - 1);
                } else {
                    map.remove(nums2[i]);
                }
                list.add(nums2[i]);
            }
        }

        int[] res = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
